package com.workmanager.controller;

import com.alibaba.fastjson.JSONObject;
import com.workmanager.bean.JobTaskBean;
import com.workmanager.bean.StudentBean;
import com.workmanager.bean.TeacherBean;
import com.workmanager.bean.WorkBean;
import com.workmanager.service.WorkFileService;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Created by dana on 2016/8/31.
 */
@RequestMapping("/workFile")
@Controller
public class WorkFileController {
    @Resource(name = "workFileService")
    private WorkFileService workFileService;

    /**
     * 上传文件  学生提交作业界面点击上传后的controller
     * 返回上传成功或失败的跳转界面
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/uploadfile")
    public String uploadfile(HttpServletRequest request, HttpServletResponse response){
        int jobtaskid=Integer.parseInt(request.getParameter("jobtaskid"));
        String date=new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());
        String dates=new SimpleDateFormat("yyyy/MM/dd/HH/mm/ss").format(Calendar.getInstance().getTime());
        HttpSession session=request.getSession(false);
        StudentBean student=(StudentBean) session.getAttribute("学生") ;
        WorkBean work=new WorkBean();

        try{
            MultipartHttpServletRequest multipartrequest = (MultipartHttpServletRequest) request;
            MultipartFile afile = multipartrequest.getFile("uploadfile");
            if(afile.getSize()==0){
                request.setAttribute("msgtitle", "上传失败!");
                request.setAttribute("msgcontent", "请选择文件!");
                request.setAttribute("msgurl", "/student/handInWork.jsp");
                return "/msg.jsp";
            }
            String suffix = afile.getOriginalFilename().substring(afile.getOriginalFilename().lastIndexOf("."));
            if(suffix.equals(".txt")||suffix.equals(".rar")||suffix.equals(".doc")||suffix.equals(".zip")||suffix.equals(".docx")){
                String path = "/static/file-upload";
                path = request.getSession().getServletContext().getRealPath(path);
                File file=new File(path);
                if  (!file .exists()  && !file .isDirectory())
                {
                    file.mkdir();
                }
                String filename=date+String.valueOf(jobtaskid)+afile.getOriginalFilename();
                FileOutputStream os = new FileOutputStream(path + File.separator + filename);
                IOUtils.copy(afile.getInputStream(),os);
                os.flush();
                os.close();
                String enclosure= File.separator+"static"+ File.separator+"file-upload" + File.separator + filename;
                work.setStudent_id(student.getStudent_id());
                work.setWork_date(dates);
                work.setJobTask_id(String.valueOf(jobtaskid));
                work.setWork_file(enclosure);
                work.setWork_title(filename);
                work.setWork_goodjob("否");
                boolean result=workFileService.uploadfile(work);
                if(result){
                    request.setAttribute("msgtitle", "上传成功!");
                    request.setAttribute("msgcontent", "上传作业成功!");
                    request.setAttribute("msgurl", "/student/handInWork.jsp");
                }else{
                    request.setAttribute("msgtitle", "上传失败!");
                    request.setAttribute("msgcontent", "上传作业失败!");
                    request.setAttribute("msgurl", "/student/handInWork.jsp");
                }
                return "/msg.jsp";
            }else{
                request.setAttribute("msgtitle", "上传失败!");
                request.setAttribute("msgcontent", "上传文件格式错误!请上传txt 或doc 或rar 或zip格式的文件！");
                request.setAttribute("msgurl", "/student/handInWork.jsp");
                return "/msg.jsp";
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        request.setAttribute("msgtitle", "上传失败!");
        request.setAttribute("msgcontent", "上传作业失败!");
        request.setAttribute("msgurl", "/student/handInWork.jsp");
        return "/msg.jsp";

    }

    /**
     * 进入学生上交作业的页面
     * 获取学生的作业上交情况以及所有该学生的作业
     * @return
     */
    @RequestMapping("/getworkofstudent")
    public void getworkofstudent(HttpServletRequest request, HttpServletResponse response){
        HttpSession session=request.getSession(false);
        StudentBean student= (StudentBean) session.getAttribute("学生");
        List<JobTaskBean> works=workFileService.getworksbystudentid(Integer.parseInt(student.getStudent_id()));
        List<WorkBean> studentworks = workFileService.getstudentworks(Integer.parseInt(student.getStudent_id()));
        JSONObject json = new JSONObject();
        json.put("works",works);
        json.put("studentworks",studentworks);
        try {
            response.getWriter().print(json.toJSONString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 进入分享优秀作业的页面
     * 获得默认项目id为第一个的项目下的优秀作业
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/findgoodjob")
    public void findgoodjob(HttpServletRequest request, HttpServletResponse response){
        HttpSession session=request.getSession(false);
        TeacherBean teacher= (TeacherBean) session.getAttribute("教师");
        String workid=request.getParameter("workid");
        JSONObject json = new JSONObject();
        List<WorkBean> goodjobs;
        if(workid==null){
            List<JobTaskBean> jobtasks = workFileService.getjobtasksbyteacherid(Integer.parseInt(teacher.getTeacher_id()));
            if(jobtasks!=null){
                goodjobs = workFileService.getgoodworksbyjobid(Integer.valueOf(jobtasks.get(0).getJobTask_id()));
                json.put("goodjobs",goodjobs);
                json.put("jobtasks",jobtasks);
                json.put("workid",jobtasks.get(0).getJobTask_id());
            }else{
                json.put("goodjobs",null);
                json.put("jobtasks",null);
            }
        }else{
            goodjobs = workFileService.getgoodworksbyjobid(Integer.valueOf(workid));
            json.put("goodjobs",goodjobs);
            json.put("workid",workid);
        }
        try {
            response.getWriter().print(json.toJSONString());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 用于取消分享优秀作业，返回成功或失败的跳转界面
     * @return
     */
    @RequestMapping("/stopshare")
    public String stopshare(HttpServletRequest request, HttpServletResponse response){
        int jobtaskid=Integer.parseInt(request.getParameter("jobtaskid"));
        String msgurl="/teacher/shareGoodJob.jsp";
        boolean result = workFileService.stopsharegoodwork(jobtaskid);
        if(result){
            request.setAttribute("msgtitle", "取消成功!");
            request.setAttribute("msgcontent", "取消成功!");
            request.setAttribute("msgurl", msgurl);
        }else {
            request.setAttribute("msgtitle", "取消失败!");
            request.setAttribute("msgcontent", "取消失败!");
            request.setAttribute("msgurl", msgurl);
        }
        return "/msg.jsp";
    }

    public WorkFileService getWorkFileService() {
        return workFileService;
    }

    public void setWorkFileService(WorkFileService workFileService) {
        this.workFileService = workFileService;
    }
}
